package com.kla.power.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kla.power.config.LogPointer;
import com.kla.power.entity.RoleEntity;
import com.kla.power.service.IRoleService;
import com.kla.power.util.ResultBody;
import com.kla.power.util.SnowflakeIdWorker;
import com.kla.power.util.StateEnum;
import com.kla.power.util.StateException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author WuZH
 * @since 2024-06-02
 */
@RestController
@RequestMapping ("/role")
@CrossOrigin (value = "*", maxAge = 3600)
public class RoleController {


    @Resource
    private IRoleService iRoleService;

    @RequestMapping ("queryList")
    @LogPointer ("查询角色列表")
    public ResultBody queryList (@RequestBody RoleEntity roleEntity) {
        List<RoleEntity> roleEntities = iRoleService.queryList ( roleEntity );
        return ResultBody.success ( roleEntities, iRoleService.queryCount ( roleEntity ) );
    }

    @RequestMapping ("querySingle")
    @LogPointer ("查询角色详情")
    public ResultBody querySingle (@RequestBody RoleEntity roleEntity) {
        roleEntity = iRoleService.querySingle ( roleEntity );
        return ResultBody.success ( roleEntity );
    }

    @RequestMapping ("saveSingle")
    @LogPointer ("保存角色")
    public ResultBody saveSingle (@RequestBody RoleEntity roleEntity) {
        roleEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        roleEntity = iRoleService.saveSingle ( roleEntity );
        return ResultBody.success ( roleEntity );
    }

    @RequestMapping ("updateSingle")
    @LogPointer ("更新角色")
    public ResultBody updateSingle (@RequestBody RoleEntity roleEntity) {
        roleEntity = iRoleService.updateSingle ( roleEntity );
        return ResultBody.success ( roleEntity );
    }

    @RequestMapping ("deleteSingle")
    @LogPointer ("删除角色")
    public ResultBody deleteSingle (@RequestBody RoleEntity roleEntity) {
        int update = iRoleService.getBaseMapper ().update ( roleEntity, new UpdateWrapper<RoleEntity> ().set ( "isUsed", 0 ).eq ( "id", roleEntity.getId () ) );
        if ( update == 0 ) {
            throw new StateException ( StateEnum.DELETE_EXCE );
        }
        return ResultBody.success ( roleEntity );
    }

}
